package cn.christ.com.mobilesafe.common.utils.downloadapputils;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import cn.christ.com.mobilesafe.common.utils.LogUtils;


/**
 * 广播接收者，下载完成或者下载通知栏被点击
 */
public class DownloadReceiver extends BroadcastReceiver {
    private String mimeType = "application/vnd.android.package-archive";
    private String DOWNLOADID = "downloadid";

    /**
     * 广播接受到要下载apk
     *
     * @param context
     * @param intent
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        //下载apk广播
        if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            //这里可以取得下载的id,这样就可以知道哪个文件下载完成了，适用于多个下载任务的监听
            long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            installApk(context, downloadId);
        } else if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) { //等于通知栏被点击
            //处理，如果还未完成下载，用户点击notification,跳转到下载中心
            Intent viewDownloadIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
            viewDownloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(viewDownloadIntent);
        }

    }

    /**
     * 安装apk
     *
     * @param context
     * @param downloadId
     */
    private void installApk(Context context, long downloadId) {
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Intent install = new Intent(Intent.ACTION_VIEW);
        //获取到下载的uri,如果uri不为空，安装apk.否则报错
        Uri downloadFileUri = downloadManager.getUriForDownloadedFile(downloadId);
        if (downloadFileUri != null) {
            LogUtils.d(downloadFileUri.toString());
            install.setDataAndType(downloadFileUri, mimeType);
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(install);
        } else {
            LogUtils.d("download error");
        }
    }


}